<?php

class UserController extends Zend_Controller_Action {
	protected $_userId; // eingeloggter User
	protected $_cache;

	/**
	 *  kontrollieren ob User eingeloggt
	 *  user-model an view übergeben
	 */
	public function init() {
		// initialize cache
		$this->_cache = Zend_Cache::factory( 'Core',
			'APC',
			array('lifeTime' => 300, 'automatic_serialization' => true));
		$r = Zend_Registry::getInstance();
		$r->pogCache = $this->_cache;

		$userLogin  = $this->_helper->isloggedin();
		if ($userLogin!=null) {
		$this->_userId = $userLogin->getId();
		}
		else {
		  $this->_userId = 0;
		}
		$this->view->userLogin = $userLogin;
	}

	//----- A c t i o n s -------------------------------------------------

	public function indexAction() {

		return $this->_helper->redirector('list');
	}

	/**
	 *  Userliste
	 */
	public function listAction() {
		$user_mp = new Application_Model_UserMapper();
		$user = new Application_Model_User();

		if (!$this->view->users = $this->_cache->load('konstkey')) {
		    $this->view->users = $user_mp->fetchAll();
		    $this->_cache->save($this->view->users,'konstkey');

	     }

	}
	/**
	 *   User id aus URL, wenn nicht vorhanden aus Login-session)
	 *   Blogrecords des Users
	 */
	public function showAction() {
		//Löschen Blog-Eintrag mit Delete buttom
		if ($this->getRequest()->isPost()) {
			if ($this->getRequest()->getParam("delete")) {
				$flashMessenger = $this->_helper->getHelper('FlashMessenger');
				$blogId = (int) $this->getRequest()->getParam("id");

				$mapper = new Application_Model_BlogMapper();

				// User aus DB holen und mit session-uid vergleichen
				$blogEntry = $mapper->find($blogId);
				if ($blogEntry->getUserid() == $this->_userId) {
					$blogEntry->setId($this->getRequest()->getParam("id"));
					$mapper->deleteRow($blogEntry->getId());
					$flashMessenger->addMessage('Record deleted');
					return $this->_redirect($this->view->url());
				} else {
					$flashMessenger->addMessage('keine Berechtigung');
					return $this->_redirect($this->view->url());
				}
			}
		}

		// falls keine userId über URL
		$uid = (int) $this->_getParam('userId');
		if ($uid == 0) {
			$uid = $this->_userId;
		}

		$user_mp = new Application_Model_UserMapper();
		$this->view->user = $user_mp->find($uid );

		if (!$this->view->blogs = $this->_cache->load("$uid")) {
			$blog = new Application_Model_BlogMapper();
			$this->view->blogs = $blog->fetchAll($uid);
			$this->_cache->save($this->view->blogs,"$uid");
		}

	}

}



